﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FastMvc
{
    public class DBHelper
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static string ConnectionString = "Database=mvc_test;Data Source=10.1.55.44;Port=3306;User Id=auggie;Password=123456;Charset=utf8;";

        /// <summary>
        /// 短连接，自动关闭
        /// </summary>
        public static SqlSugarClient SqlSugarDB
        {
            get
            {
                var _connectionString = ConnectionString;
                SqlSugarClient _db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = _connectionString,//必填, 数据库连接字符串
                    DbType = SqlSugar.DbType.MySql,         //必填, 数据库类型
                    IsAutoCloseConnection = true,       //默认false, 直到主动关闭数据库连接, 设置为true无需使用using或者Close操作
                    InitKeyType = InitKeyType.SystemTable    //默认SystemTable, 字段信息读取, 如：该属性是不是主键，是不是标识列等等信息
                });

                return _db;
            }
        }

        /// <summary>
        /// DBFirst
        /// 1. 去除公共字段，如sId, sOrgId等
        /// 2. 公共类库的继承，默认需要继承至TEntity
        /// </summary>
        /// <param name="tables">需要转换的表</param>
        /// <param name="TEntity">是否继承至基础TEntity</param>
        public static void DBFirst(string[] tables, string Dir, bool TEntity = false, string NameSpace = "")
        {
            var ifirst = SqlSugarDB.DbFirst;

            if (TEntity)
            {
                if (tables != null && tables.Length > 0)
                {
                    ifirst = ifirst.Where(tables);
                }
                string[] EntityColumns = new string[] { "sId", "iDelete", "dCreateTime", "dUpdateTime" };
                ifirst = ifirst
                    .WhereColumns(col => !EntityColumns.Contains(col))
                    .SettingNamespaceTemplate(np=>np+ "using FastMvc.Crud;\r\n")
                    .SettingClassTemplate(clName =>
                    {
                        return clName.Replace("public partial class {ClassName}", "public partial class {ClassName}: DBEntity");
                    });
            }
            if (string.IsNullOrEmpty(NameSpace))
            {
                NameSpace = "JQ.SAAS.Entity";
            }
            ifirst.CreateClassFile(Dir, NameSpace);
        }
    }
}
